package com.wlb365.financing.modules.sys.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlb365.financing.common.annotation.DataScope;
import com.wlb365.financing.common.utils.StringUtils;
import com.wlb365.financing.modules.sys.entity.User;
import com.wlb365.financing.modules.sys.mapper.DeptMapper;
import com.wlb365.financing.modules.sys.mapper.RoleMapper;
import com.wlb365.financing.modules.sys.mapper.UserMapper;
import com.wlb365.financing.modules.sys.service.IUserService;
import com.wlb365.financing.modules.sys.vo.UserQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 概述：
 * </p>
 *
 * @author zwh
 * @version 1.0
 * @copyRight 北京微利宝信息技术有限公司  All right reserved.
 * @date 2020/3/21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Override
    @DataScope
    public Page<User> listUserPage(UserQueryVO queryVO) {
        Page<User> page = new Page<>(queryVO.getCurrent(), queryVO.getSize());
        List<User> users = baseMapper.selectUserList(queryVO, page);
        return page.setRecords(users);
    }

    @Override
    public User getByUsername(String username) {
        User user = super.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if(ObjectUtil.isNotEmpty(user)){
            user.setRoles(roleMapper.getUserRoles(user.getId()));
            if (StringUtils.isNotEmpty(user.getDeptId())) {
                user.setDept(deptMapper.selectById(user.getDeptId()));
            }
        }
        return user;
    }

    @Override
    public void updateUserPassword(String id, String password) {
        super.update(new LambdaUpdateWrapper<User>()
                .set(User::getPassword, password)
                .eq(User::getId, id));
    }

    @Override
    public User getUserByAccount(String accountId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccountId, accountId);
        return baseMapper.selectOne(queryWrapper);
    }

}
